package com.starblink.wishlist.wishboards.ui

import android.view.LayoutInflater
import android.view.ViewGroup
import androidx.recyclerview.widget.RecyclerView
import com.starblink.android.basic.base.fragment.BaseTVMFragment
import com.starblink.android.basic.ext.gone
import com.starblink.android.basic.ext.toast
import com.starblink.android.basic.ext.toastWishlist
import com.starblink.android.basic.ext.visible
import com.starblink.android.basic.network.base.SkGqlClient
import com.starblink.android.basic.user.UserDataCenter
import com.starblink.android.basic.util.FlowCountDownTimer
import com.starblink.android.basic.util.bus.FlowBus
import com.starblink.android.basic.util.bus.FlowConst
import com.starblink.basic.util.log.YYLogUtils
import com.starblink.rocketreserver.fragment.ProductF
import com.starblink.wishlist.databinding.FragmentWishBoardsBinding
import com.starblink.wishlist.wishboards.ui.bean.RvAddBoardsEntry
import com.starblink.wishlist.wishboards.ui.bean.RvBoardItemEntry
import com.starblink.wishlist.wishboards.ui.bean.RvNoBoardsEntry
import com.starblink.wishlist.wishboards.ui.part.WishBoardsPart
import com.starblink.wishlist.wishlistdetails.ui.bean.RvBoardDetailsItemEntry

/**
 *
 */
class WishBoardsFragment : BaseTVMFragment<FragmentWishBoardsBinding, WishBoardsVM>() {

    companion object {
        private const val TAG = "WishBoardsFragment"
        fun obtainFragment(): WishBoardsFragment {
            return WishBoardsFragment()
        }
    }

    lateinit var wishBoardsPart: WishBoardsPart

    override fun getViewBinding(
        inflater: LayoutInflater,
        container: ViewGroup?
    ): FragmentWishBoardsBinding {
        return FragmentWishBoardsBinding.inflate(inflater, container, false)
    }


    /**
     * 初始化数据
     */
    override fun initData() {
        viewModel.initSomeData()
        wishBoardsPart = WishBoardsPart(mActivity, viewBinding, viewModel).apply {
            handleVM()
        }

        viewBinding.state.refreshing()
        viewBinding.page.onMutRefresh {
            refreshMainData()
        }.refresh()

        viewBinding.page.onMutLoadMore {
            YYLogUtils.e("开始加载更多")
            viewModel.loadMore(hasFinish = {
                viewBinding.page.finishLoadMore()
            })
        }

    }

    //切换多选模式
    fun intoMutiSelect(choiceMode_2: Boolean) {
        wishBoardsPart.mutiChange(choiceMode_2)
    }

    private fun refreshMainData(
        showPageDialog: Boolean = false,
        showSimpleDialog: Boolean = false
    ) {

        if (!UserDataCenter.isLogin()) {
            viewBinding.page.finishRefresh()
            return
        }
        if (showPageDialog) {
            viewBinding.state.showLoading()
        }

        viewModel.initRefresh(showSimpleDialog = showSimpleDialog, hasFinish = {
            viewBinding.state.showContent()
            viewBinding.page.finishRefresh()

            //是否开启加载更多
//            if (viewModel.autoLoadMore) {
//                viewBinding.page.setEnableLoadMore(true)
//            } else {
//                viewBinding.page.setEnableLoadMore(false)
//            }
        })
    }


    var mustBeRefresh = false

    override fun onResume() {
        canRefresh()
        super.onResume()
        YYLogUtils.e("resume 3333 ${this.isVisible}")
    }

    fun canRefresh() {
        if (mustBeRefresh) {
            refreshMainData()
            mustBeRefresh = false
        }
    }

    fun syncPageSelectIndex(pageIndex: Int) {
        viewModel.currentPageIndex = pageIndex
    }

    override fun startObserve() {
        //退出登录
        FlowBus.with<Boolean>(FlowConst.LOGIN_STATUS_CHANGE).register(this) {
            mustBeRefresh = true
            if (!UserDataCenter.isLogin()) {
                FlowBus.boolFlowBusNotify(FlowConst.IN_WISHLIST_BOARD_BUT_NOT_LOGIN)
            }
        }
        //创建心愿单成功
        FlowBus.with<Boolean>(FlowConst.WISHLIST_BOARD_REFRESH).register(this) {
            mustBeRefresh = true
        }

        FlowBus.with<List<ProductF>>(FlowConst.WISHLIST_DELETE_PRODUCT_VIEW)
            .register(this) { prdBusList ->
                mustBeRefresh = true
            }


        //显示删除弹窗
        FlowBus.with<Int>(FlowConst.WISH_BOARDS_SHOW_TOAST).register(this) {
            if (-1 != it) {

                toastWishlist("Removed successfully")
//                viewBinding.llMutiAddSuccessToast.visible()
//                viewBinding.llMutiAddSuccessToastTxt.text = "Removed successfully"
//
//                FlowCountDownTimer(time = 2).start(callBack = {
//                }, onFinish = {
//                    viewBinding.llMutiAddSuccessToast.gone()
//                })

                if (viewModel.getCurrentItemDataSize() == 0) {
                    refreshMainData(showSimpleDialog = true)
                }
            }

        }

//        //下边的滚动判断和这个是绑在一起用的----->WISHLIST_DELETE_PRODUCT_VIEW
//        viewBinding.rv.addOnScrollListener(object : RecyclerView.OnScrollListener() {
//            override fun onScrolled(recyclerView: RecyclerView, dx: Int, dy: Int) {
//                super.onScrolled(recyclerView, dx, dy)
////                if (!viewBinding.rv.canScrollVertically(1)) {
////                    //滑动到底部
////                }
//                if (!viewBinding.rv.canScrollVertically(-1)) {
//                    //滑动到顶部
//                    if (mustBeRefresh && this@WishBoardsFragment.isVisible) {
//                        refreshMainData(showSimpleDialog = true)
//                        mustBeRefresh = false
//                    }
//                }
//            }
//        })


        viewModel.mBoardsObserver.observe(this) {
            showOrHideSetting(it)
        }
    }

    private fun showOrHideSetting(arr: ArrayList<Any>) {
        var num = 0
        arr.forEach { item ->
            if (item is RvBoardItemEntry) {
                num++
            }
        }
        var noData = false
        if (num == 0 && arr.size > 0 && arr[0] is RvAddBoardsEntry) {
            arr.removeAt(0)
            arr.add(0, RvNoBoardsEntry())
            noData = true
        }
        if (num > 0 && arr[0] is RvNoBoardsEntry) {
            arr.removeAt(0)
            arr.add(0, RvAddBoardsEntry())
            noData = false
        }
        mDataChangeListener?.invoke(num, viewModel.selectAll, noData)
        //写后边
        wishBoardsPart.dataChange(arr)
    }


    private var mDataChangeListener: ((Int, Boolean, Boolean) -> Unit)? = null

    fun setDataChangeListener(listener: (Int, Boolean, Boolean) -> Unit) {
        this.mDataChangeListener = listener
    }

    fun hideBtmLay(){
        viewModel.choiceMode = false
        viewBinding.llMutiBtmLay.gone()
    }

}